# -*- coding: utf-8 -*-
import ast
import hashlib
import json
from collections import OrderedDict

import requests
from django.conf import settings

from async import async_job
from common.channel.pay import check_channel_order
from common.order import db as order_db
from common.order.model import PAY_STATUS
from common.utils import track_logging
from common.utils.exceptions import ParamError

_LOGGER = track_logging.getLogger(__name__)

APP_CONF = {
    '20000051': {
        #  jbcpay 支付宝红包 2.7% 10-10000 witch
        'API_KEY': '5YX5IZVNASOOZUP4Z0UAX2M7FBVFIELIEEMEXEY6XGX5YX85GXZBGFG7BLTOBVQJPIIUO3YGGHRYUNJ4LICFNSYSIYBY3AN3JIRI7Y7OSEANWIY0791DH6HGZZRRVOWU',
        'gateway': 'http://pay.jbocai.vip/api/pay/create_order?params=',
        'query_gateway': 'http://pay.jbocai.vip/api/pay/query_order?params=',
        'appId': '603d3d6dbf594be6abb2874b02817e9e'
    },
    '20000054': {
        #  jbcpay 支付宝红包 2.7% 10-10000 dwc
        'API_KEY': '3S3O7LGDUHHTMB3HMSQBFDXOGY0ZMYKIXZQLTCM4FK2AZ7IQXLTVCAINUM06QQ3OVZRVIT1UBPC7QM9XKA1XAO3X3BTTG2JZYYIBG6DCIHUPO34FG3HC7SYHNLYXDD0S',
        'gateway': 'http://pay.jbocai.vip/api/pay/create_order?params=',
        'query_gateway': 'http://pay.jbocai.vip/api/pay/query_order?params=',
        'appId': '024d3ad868624c82a3bf8a95d2c53a02'
    },
}


def _get_api_key(mch_id):
    return APP_CONF[mch_id]['API_KEY']


def _get_app_id(mch_id):
    return APP_CONF[mch_id]['appId']


def _get_gateway(mch_id):
    return APP_CONF[mch_id]['gateway']


def _get_query_gateway(mch_id):
    return APP_CONF[mch_id]['query_gateway']


def _gen_sign(s):
    m = hashlib.md5()
    m.update(s.encode('utf8'))
    sign = m.hexdigest().upper()
    return sign


def generate_sign(parameter, key):
    s = ''
    for k in sorted(parameter.keys()):
        if k != 'sign' and parameter[k] != '':
            s += '%s=%s&' % (k, parameter[k])
    s += 'key=%s' % key
    return _gen_sign(s)


def verify_notify_sign(params, key):
    sign = params['sign']
    params.pop('sign')
    calculated_sign = generate_sign(params, key)
    if sign.upper() != calculated_sign.upper():
        _LOGGER.info("jbcpay sign: %s, calculated sign: %s", sign, calculated_sign)
        raise ParamError('sign not pass, data: %s' % params)


def _get_pay_type(service):
    if service == 'alipay_scan':
        return 8006
    elif service == 'alipay_h5':
        return 8007
    elif service == 'alipay_single':
        return 8015
    return 8006


def verify_sign(params, key):
    sign = params['sign']
    params.pop('sign')
    calculated_sign = generate_sign(params, key)
    if sign.upper() != calculated_sign.upper():
        _LOGGER.info("ffpay sign: %s, calculated sign: %s", sign, calculated_sign)
        raise ParamError('sign not pass, data: %s' % params)


def create_charge(pay, pay_amount, info):
    service = info.get('service')
    app_id = info['app_id']
    api_key = _get_api_key(app_id)
    parameter_dict = OrderedDict((
        ('mchId', int(app_id)),
        ('appId', _get_app_id(app_id)),
        ('productId', _get_pay_type(service)),
        ('mchOrderNo', str(pay.id)),
        ('currency', 'CNY'),
        ('amount', int(pay_amount * 100)),
        ('notifyUrl', '{}/pay/api/{}/jbcpay/{}'.format(settings.NOTIFY_PREFIX, settings.NOTIFY_PATH, app_id)),
        ('returnUrl', '{}/pay/api/{}/jbcpay/{}'.format(settings.NOTIFY_PREFIX, settings.RETURN_PATH, str(pay.id))),
        ('subject', 'charge'),
        ('body', 'charge'),
        ('extra', ''),
    ))
    parameter_dict['sign'] = generate_sign(parameter_dict, api_key)
    _LOGGER.info("jbcpay create: %s, order_id is: %s", json.dumps(parameter_dict), parameter_dict['mchOrderNo'])
    url = _get_gateway(app_id) + json.dumps(parameter_dict)
    response = requests.post(url, timeout=3, verify=False)
    res_obj = json.loads(response.text)
    _LOGGER.info("jbcpay create charge response.text: %s", response.text)
    verify_sign(res_obj, api_key)
    return {'charge_info': ast.literal_eval(res_obj['payParams'])['qrcode']}


# success
def check_notify_sign(request, app_id):
    api_key = _get_api_key(app_id)
    _LOGGER.info("jbcpay notify body: %s", request.body)
    data = dict(request.POST.iteritems())
    _LOGGER.info("jbcpay notify data: %s, order_id is: %s", data, data['mchOrderNo'])
    verify_notify_sign(data, api_key)
    pay_id = data['mchOrderNo']
    if not pay_id:
        _LOGGER.error("fatal error, out_trade_no not exists, data: %s", data)
        raise ParamError('jbcpay event does not contain pay ID')

    pay = order_db.get_pay(int(pay_id))
    if not pay:
        raise ParamError('pay_id: %s invalid' % pay_id)
    if pay.status != PAY_STATUS.READY:
        raise ParamError('pay %s has been processed' % pay_id)

    mch_id = pay.mch_id
    trade_status = str(data['status'])
    trade_no = data['payOrderId']
    total_fee = float(data['amount']) / 100.0
    extend = {
        'trade_status': trade_status,
        'trade_no': trade_no,
        'total_fee': total_fee
    }
    check_channel_order(pay_id, total_fee, app_id)
    # 支付状态,0-订单生成,1-支付中,2-支付成功,3-业务处理完成
    if trade_status == '2':
        _LOGGER.info('jbcpay check order success, mch_id:%s pay_id:%s' % (mch_id, pay_id))
        order_db.add_pay_success(mch_id, pay_id, total_fee, trade_no, extend)
        # async notify
        async_job.notify_mch(pay_id)


def query_charge(pay_order, app_id):
    ''' 查询订单 '''
    # prepare param
    pay_id = pay_order.id
    api_key = _get_api_key(app_id)
    parameter_dict = OrderedDict((
        ('mchId', int(app_id)),
        ('appId', _get_app_id(app_id)),
        ('payOrderId', pay_order.third_id),
        ('mchOrderNo', pay_id),
    ))
    parameter_dict['sign'] = generate_sign(parameter_dict, api_key)
    _LOGGER.info("jbcpay query data: %s, order_id: %s", json.dumps(parameter_dict), parameter_dict['mchOrderNo'])
    url = _get_query_gateway(app_id) + json.dumps(parameter_dict)
    response = requests.post(url, timeout=3, verify=False)
    _LOGGER.info("jbcpay query rsp data: %s", response.text)
    if response.status_code == 200:
        data = json.loads(response.text)
        trade_status = str(data['status'])
        trade_no = str(data['payOrderId'])
        total_fee = float(data['amount']) / 100.0
        extend = {
            'trade_status': trade_status,
            'trade_no': trade_no,
            'total_fee': total_fee
        }
        # 支付状态,0-订单生成,1-支付中,2-支付成功,3-业务处理完成
        if trade_status in ['2', '3']:
            _LOGGER.info('jbcpay query order success, user_id:%s pay_id:%s' % (pay_order.mch_id, pay_id))
            order_db.add_pay_success(pay_order.mch_id, pay_order.id,
                                     total_fee, trade_no, extend)
            async_job.notify_mch(pay_order.id)
    else:
        _LOGGER.warn('jbcpay data error, status_code: %s', response.status_code)
